package com.eschool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eschool.mapper.CourseMapper;
import com.eschool.mapper.ScoreMapper;
import com.eschool.mapper.StudentMapper;
import com.eschool.mapper.UserMapper;
import com.eschool.pojo.*;
import com.eschool.service.CourseService;

import io.netty.util.internal.StringUtil;
import io.swagger.models.auth.In;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import java.util.Set;
import java.util.stream.Collectors;


@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    CourseMapper courseMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ScoreMapper scoreMapper;
    @Autowired
    StudentMapper studentMapper;


    @Override
    public int ChooseCourse(ChooseCourseDTO chooseCourseDTO) {
        QueryWrapper q1 = new QueryWrapper();
        QueryWrapper q2 = new QueryWrapper();

        q1.eq("studentId", chooseCourseDTO.getStudentId());
        q2.eq("courseid", chooseCourseDTO.getCourseid());
        StudentDAO studentDAO = studentMapper.selectOne(q1);
        CourseDAO courseDAO = courseMapper.selectOne(q2);
        ScoreDAO scoreDAO = new ScoreDAO();
        scoreDAO.setStudentId(chooseCourseDTO.getStudentId());
        scoreDAO.setCourseid(chooseCourseDTO.getCourseid());
        scoreDAO.setGrade(courseDAO.getClassgrade());
        scoreDAO.setCoursename(courseDAO.getCoursename());
        scoreDAO.setTeacher(courseDAO.getTeacher());
        scoreDAO.setScore(null);
        scoreDAO.setScoreid(ShortUniqueId.generate());
        scoreDAO.setWeekday(courseDAO.getWeekday());
        scoreDAO.setStartTime(courseDAO.getStartTime());
        scoreDAO.setEndTime(courseDAO.getEndTime());

        int insertRow = scoreMapper.insert(scoreDAO);
        return insertRow;
    }

    @Override

    public List<ScoreDAO> getScoreByInfo(ScoreDTO scoreDTO) {

        if (scoreDTO == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (scoreDTO.getStudentId() == null) {
            throw new IllegalArgumentException("学号不能为空");
        }

        QueryWrapper<ScoreDAO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentId", scoreDTO.getStudentId())
                .isNotNull("score")    // 过滤 NULL
                .ne("score", "");     // 过滤空字符串（可选，根据需求）
        if (StringUtils.isNotBlank(scoreDTO.getCoursename())) {
            queryWrapper.like("coursename", scoreDTO.getCoursename());
        }
        if (StringUtils.isNotBlank(scoreDTO.getTeacher())) {
            queryWrapper.like("teacher", scoreDTO.getTeacher());
        }
        if (StringUtils.isNotBlank(scoreDTO.getGrade())) {
            queryWrapper.like("grade", scoreDTO.getGrade());
        }


        return scoreMapper.selectList(queryWrapper);
    }

    public List<CourseVO> getCourses(String studentId, String grade) {
        return courseMapper.getCourses(studentId, grade);
    }

    @Override
    public List<CourseDAO> getConflictCourse(String studentId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentId",studentId);
        queryWrapper.isNull("score");
        List<ScoreDAO> scoreDAOS = scoreMapper.selectList(queryWrapper);
        List<CourseDAO> courseDAOs = new ArrayList<>();
        for(ScoreDAO scoreDAO:scoreDAOS){
            QueryWrapper q1 = new QueryWrapper();
            List<CourseDAO> courseDAOForEach;
            q1.eq("weekday",scoreDAO.getWeekday());
            q1.ge("endTime",scoreDAO.getStartTime());
            q1.le("startTime",scoreDAO.getEndTime());
            courseDAOForEach = courseMapper.selectList(q1);
            for(CourseDAO item :  courseDAOForEach){
                courseDAOs.add(item);
            }
        }
        return courseDAOs;
    }

    @Override
    public List<CourseDAO> getCourseByGrade(String studentId,String academicYear, String semester) {
        QueryWrapper q1 = new QueryWrapper();
        q1.eq("studentId",studentId);
        StudentDAO studentDAO = studentMapper.selectOne(q1);
        Integer grade = (Integer.parseInt(academicYear.substring(0,4)) - Integer.parseInt(studentDAO.getGrade().substring(0,4))) * 2 + 1;
        if(semester == "二") grade++;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("classgrade",grade);
        return courseMapper.selectList(queryWrapper);
    }

    @Override
    public List<CourseDAO> getGradeConflictCourses(String studentId, String academicYear, String semester) {  //实际上就是前面两个合起来
        QueryWrapper q1 = new QueryWrapper();
        q1.eq("studentId",studentId);
        StudentDAO studentDAO = studentMapper.selectOne(q1);
        Integer grade = (Integer.parseInt(academicYear.substring(0,4)) - Integer.parseInt(studentDAO.getGrade().substring(0,4))) * 2 + 1;
        if(semester == "二") grade++;

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentId",studentId);
        queryWrapper.isNull("score");
        List<ScoreDAO> scoreDAOS = scoreMapper.selectList(queryWrapper);
        List<CourseDAO> courseDAOs = new ArrayList<>();
        for(ScoreDAO scoreDAO:scoreDAOS){
            QueryWrapper q2 = new QueryWrapper();
            List<CourseDAO> courseDAOForEach;
            q2.ne("courseid",scoreDAO.getCourseid());
            q2.eq("classgrade",grade);
            q2.eq("weekday",scoreDAO.getWeekday());
            q2.ge("endTime",scoreDAO.getStartTime());
            q2.le("startTime",scoreDAO.getEndTime());
            courseDAOForEach = courseMapper.selectList(q2);
            for(CourseDAO item :  courseDAOForEach){
                courseDAOs.add(item);
            }
        }
        return courseDAOs;
    }

    @Override
    public List<CourseDAO> getGradeRightCourses(String studentId, String academicYear, String semester) {
        List<CourseDAO> courseDAOs = getCourseByGrade(studentId,academicYear,semester);
        List<CourseDAO> conflictCourseDAOs = getConflictCourse(studentId);

        Set<String> conflictIds = conflictCourseDAOs.stream()
                .map(CourseDAO::getCourseid)
                .collect(Collectors.toSet());
        courseDAOs.removeIf(course -> conflictIds.contains(course.getCourseid()));
        return courseDAOs;
    }

    @Override
    public List<ScoreDAO> getChoosenCourseByStudentId(String studentId) {
        QueryWrapper q1 = new QueryWrapper();
        q1.eq("studentId",studentId);
        q1.isNull("score");
        List<ScoreDAO>  scoreDAOList = scoreMapper.selectList(q1);
        return scoreDAOList;
    }

    @Override
    public List<CourseDAO> getChosenCourse(String studentId) {
        List<ScoreDAO> scoreDAOS = getChoosenCourseByStudentId(studentId);
        List<CourseDAO> courseDAOS = new ArrayList<>();
        for(ScoreDAO item :scoreDAOS){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("courseid",item.getCourseid());
            CourseDAO courseDAO = courseMapper.selectOne(queryWrapper);
            courseDAOS.add(courseDAO);
        }
        return courseDAOS;
    }

    @Override
    public int DeleteCourse(String studentId, String courseid) {
        QueryWrapper  queryWrapper = new QueryWrapper();
        queryWrapper.eq("studentId",studentId);
        queryWrapper.eq("courseid",courseid);
        return scoreMapper.delete(queryWrapper);
    }


    private StudentDAO getStudentOrThrow(String studentId) {
        StudentDAO student = studentMapper.selectOne(new QueryWrapper<StudentDAO>()
                .eq("studentId", studentId));
        if (student == null) {
            throw new RuntimeException("学生不存在");
        }
        return student;
    }

    private int calculateBaseGrade(StudentDAO student, String academicYear) {
        int currentYear = Integer.parseInt(academicYear.substring(0, 4));
        int enrollYear = Integer.parseInt(student.getGrade().substring(0, 4));
        return (currentYear - enrollYear) * 2 + 1;
    }

    private int adjustGradeBySemester(int baseGrade, String semester) {
        return "二".equals(semester) ? baseGrade + 1 : baseGrade;
    }



}
